package org.jeecg.modules.monitoring.j_monitoring.controller;

import java.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.monitoring.j_monitoring.utils.EquipmentUtils;
import org.jeecg.modules.monitoring.j_monitoring.entity.*;

import org.jeecg.modules.monitoring.j_monitoring.mapper.MGlNetworkResourceMapper;
import org.jeecg.modules.monitoring.j_monitoring.service.IMGlNetworkResourceService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.monitoring.j_monitoring.service.impl.GatewaySystemFdnServiceImpl;
import org.jeecg.modules.monitoring.j_monitoring.service.impl.GatewayWarningServiceImpl;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 网络资源(管理)
 * @Author: xiaoyq
 * @Date:   2023-01-11
 * @Version: V1.0
 */
@Api(tags="网络资源(管理)")
@RestController
@RequestMapping("/j_monitoring/mGlNetworkResource")
@Slf4j
public class MGlNetworkResourceController extends JeecgController<MGlNetworkResource, IMGlNetworkResourceService> {
	@Resource
	private MGlNetworkResourceMapper mGlNetworkResourceMapper;

	@Resource
	private GatewaySystemFdnServiceImpl systemFdnService;
	@Resource
	private GatewayWarningServiceImpl warningService;


	/**
	 * 分页列表查询
	 *
	 * @param mGlNetworkResource
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "网络资源(管理)-分页列表查询")
	@RequiresPermissions("网络资源:查询")
	@ApiOperation(value="网络资源(管理)-分页列表查询", notes="网络资源(管理)-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MGlNetworkResource mGlNetworkResource,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Result<Page<MGlNetworkResource>> result=new Result<>();
		Page<MGlNetworkResource> pagelist = new Page(pageNo, pageSize);
		QueryWrapper<MGlNetworkResource> queryWrapper = QueryGenerator.initQueryWrapper(mGlNetworkResource, req.getParameterMap());

		pagelist=mGlNetworkResourceMapper.getPageList(pagelist,queryWrapper);
		List<MGlNetworkResource> networkResourceList  = pagelist.getRecords();
		List<String> ipList = new ArrayList<>();
		for (MGlNetworkResource networkResource : networkResourceList){
			//是否是监控
			if (!mGlNetworkResource.getIsMonitor()){
				networkResource.setMonitorStatus(EquipmentUtils.getMonitorStatus(networkResource.getWhetherToMonitor()));
			}
			ipList.add(networkResource.getManageIp());

		}

		Map<String,Object> map = systemFdnService.getPingMonitor(ipList);
		if (mGlNetworkResource.getIsMonitor()){
			//查看ping返回值
			for (MGlNetworkResource networkResource : networkResourceList){
				networkResource.setMonitorStatus(map.get(networkResource.getManageIp()).toString());

				if (!"3".equals(networkResource.getMonitorStatus()) && map.get("time"+networkResource.getManageIp()) != null){
					networkResource.setResponseTime(map.get("time"+networkResource.getManageIp()).toString());
				}

			}

		}


		result.setCode(200);
		result.setSuccess(true);
		result.setResult(pagelist);
		return result;
	}

	/**
	 *   添加
	 *
	 * @param mGlNetworkResource
	 * @return
	 */
	@AutoLog(value = "网络资源(管理)-添加")
	@ApiOperation(value="网络资源(管理)-添加", notes="网络资源(管理)-添加")
	@RequiresPermissions("网络资源:添加")
	//@RequiresPermissions("org.jeecg.modules.monitoring:m_gl_network_resource:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MGlNetworkResource mGlNetworkResource) {


		MGlNetworkResource m = new MGlNetworkResource();
		QueryWrapper<MGlNetworkResource> queryWrapper = QueryGenerator.initQueryWrapper(m, new HashMap<>());
		queryWrapper.eq("equipment_no",mGlNetworkResource.getEquipmentNo());
		if (mGlNetworkResourceMapper.selectCount(queryWrapper)>0){
			return Result.error("设备编号重复，添加失败！");
		}


		service.save(mGlNetworkResource);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mGlNetworkResource
	 * @return
	 */
	@AutoLog(value = "网络资源(管理)-编辑")
	@ApiOperation(value="网络资源(管理)-编辑", notes="网络资源(管理)-编辑")
	//@RequiresPermissions("org.jeecg.modules.monitoring:m_gl_network_resource:edit")
	@RequiresPermissions("网络资源:编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody MGlNetworkResource mGlNetworkResource) {
		service.updateById(mGlNetworkResource);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "网络资源(管理)-通过id删除")
	@ApiOperation(value="网络资源(管理)-通过id删除", notes="网络资源(管理)-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.monitoring:m_gl_network_resource:delete")
	@RequiresPermissions("网络资源:删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		service.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "网络资源(管理)-批量删除")
	@ApiOperation(value="网络资源(管理)-批量删除", notes="网络资源(管理)-批量删除")
	//@RequiresPermissions("org.jeecg.modules.monitoring:m_gl_network_resource:deleteBatch")
	@RequiresPermissions("网络资源:批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.service.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	 /**
	  *  监控
	  * @return
	  */
	 @AutoLog(value = "网络资源(管理)-添加监控")
	 @ApiOperation(value="网络资源(管理)-添加监控", notes="网络资源(管理)-添加监控")
	 //@RequiresPermissions("org.jeecg.modules.monitoring:m_gl_network_resource:monitor")
	 @RequiresPermissions("网络资源:监控")
	 @RequestMapping(value = "/monitor", method = {RequestMethod.POST})
	 @Transactional(rollbackFor = Exception.class)
	 public Result<String> monitor(@RequestParam(name="ids",required=true) String ids) {
		 List<String> idList = Arrays.asList(ids.split(","));
		 if(idList.size()==0){
			 return Result.error("数据为空!");
		 }
		 UpdateWrapper<MGlNetworkResource> updateWrapper = new UpdateWrapper<>();
		 LambdaUpdateWrapper<MGlNetworkResource> lambdaUpdateWrapper = updateWrapper.lambda();
		 idList.forEach(item->lambdaUpdateWrapper.or(qr->qr.eq(MGlNetworkResource::getId,item)));
		 lambdaUpdateWrapper.set(MGlNetworkResource::getWhetherToMonitor,"1");
		 service.update(updateWrapper);
		 return Result.OK("监控添加成功!");
	 }

	 /**
	  *  取消监控
	  *
	  * @return
	  */
	 @AutoLog(value = "网络资源(管理)-取消监控")
	 @ApiOperation(value="网络资源(管理)-取消监控", notes="网络资源(管理)-取消监控")
	 @RequiresPermissions("网络资源:取消监控")
	 //@RequiresPermissions("org.jeecg.modules.monitoring:m_gl_network_resource:unmonitor")
	 @RequestMapping(value = "/unmonitor", method = {RequestMethod.POST})
	 @Transactional(rollbackFor = Exception.class)
	 public Result<String> unmonitor(@RequestParam(name="ids",required=true) String ids) {
		 List<String> idList = Arrays.asList(ids.split(","));
		 if(idList.size()==0){
			 return Result.error("数据为空!");
		 }
		 UpdateWrapper<MGlNetworkResource> updateWrapper = new UpdateWrapper<>();
		 LambdaUpdateWrapper<MGlNetworkResource> lambdaUpdateWrapper = updateWrapper.lambda();
		 idList.forEach(item->lambdaUpdateWrapper.or(qr->qr.eq(MGlNetworkResource::getId,item)));
		 lambdaUpdateWrapper.set(MGlNetworkResource::getWhetherToMonitor,"0");
		 service.update(updateWrapper);
		 return Result.OK("监控取消成功!");
	 }

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "网络资源(管理)-通过id查询")
	@RequiresPermissions("网络资源:查询")
	@ApiOperation(value="网络资源(管理)-通过id查询", notes="网络资源(管理)-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MGlNetworkResource> queryById(@RequestParam(name="id",required=true) String id) {
		MGlNetworkResource mGlNetworkResource = service.getById(id);
		if(mGlNetworkResource==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mGlNetworkResource);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param mGlNetworkResource
    */
	@RequiresPermissions("网络资源:导出")
	@ApiOperation(value="网络资源(管理)-导出", notes="网络资源(管理)-导出")
	@RequestMapping(value = "/exportXls", method = RequestMethod.GET)
    public ModelAndView exportXls(HttpServletRequest request, MGlNetworkResource mGlNetworkResource) {
        return super.exportXls(request, mGlNetworkResource, MGlNetworkResource.class, "网络资源");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("m_gl_network_resource:importExcel")
	@ApiOperation(value="网络资源(管理)-导入", notes="网络资源(管理)-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@RequiresPermissions("网络资源:导入")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MGlNetworkResource.class);
    }

	 /**
	  *
	  * @return
	  */
	 @RequestMapping(value = "/insertByEquipment", method = RequestMethod.POST)
	 public Result<?> insertByEquipment(@RequestBody EquipmentIds equipmentIds) {
		 service.insertByEquipment(equipmentIds.getIds());
		 return Result.OK("成功");
	 }

	 @GetMapping(value = "/test")
	 @AutoLog(value = "测试")
	 @ApiOperation(value = "测试", notes = "动态切换数据源")
	 public void test() {
		 service.test();
	 }

	 @Override
	 protected  void beforeImportExcel(List<MGlNetworkResource> list){
		 list.forEach(item->{
			 if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getCabinet())){
				 item.setCabinet(item.getCabinet().trim());
			 }
			 if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getMachineRoom())){
				 item.setMachineRoom(item.getMachineRoom().trim());
			 }
			 if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getPersonLiable())){
				 item.setPersonLiable(item.getPersonLiable().trim());
			 }
		 });
	 }

	 @Override
	 protected void afterImportExcel(List<MGlNetworkResource> list){
		 UpdateWrapper<MGlNetworkResource> updateWrapper = new UpdateWrapper<>();
		 updateWrapper.lambda().isNull(MGlNetworkResource::getCabinetId);
		 updateWrapper.setSql("Cabinet_id=(select id from m_cabinet where Cabinet=name LIMIT 1)");
		 this.service.update(updateWrapper);

		 updateWrapper.clear();
		 updateWrapper.lambda().isNull(MGlNetworkResource::getMachineRoomId);
		 updateWrapper.setSql("Machine_Room_Id=(select id from m_machine_room where machine_room=name LIMIT 1)");
		 this.service.update(updateWrapper);

		 updateWrapper.clear();
		 updateWrapper.lambda().isNull(MGlNetworkResource::getPersonLiableId);
		 updateWrapper.setSql("person_liable_id=(select id from sys_user where person_liable=realname LIMIT 1)");
		 this.service.update(updateWrapper);
	 }

}
